package se.thoka.twt.client.widgets;

import se.thoka.twt.client.form.HasTWTFormFieldInfo;
import se.thoka.twt.client.form.TWTFormField;
import se.thoka.twt.client.utils.Delayer;
import se.thoka.twt.client.utils.TWTSettings;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.TextBox;

public class TWTTextBox extends TWTFormField<TextBox> {
	
	private Delayer changeEventDelayer;
	
	public TWTTextBox() {
		this(generateId());
	}

	public TWTTextBox(String id) {
		this(id, null);
	}
	
	public TWTTextBox(HasTWTFormFieldInfo info) {
		this(info.name(), info.label());
	}

	public TWTTextBox(String id, String label) {
		super(id, label);
		
		changeEventDelayer = new Delayer(TWTSettings.getFormConfig().changeDelayInMillis(), new Command() {
			@Override
			public void execute() {
				fireChangeEvent();
			}
		});
	}
	
	@Override
	protected TextBox createField() {
		TextBox textBox = createTextBox();
		textBox.addKeyUpHandler(new KeyUpHandler() {
			@Override
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					requestSubmit();
				} else {
					changeEventDelayer.delay();
				}
			}
		});
		textBox.addChangeHandler(new ChangeHandler() {
			@Override
			public void onChange(ChangeEvent event) {
				changeEventDelayer.delay();
			}
		});
		textBox.addChangeHandler(new ChangeHandlerProxy());
		
		return textBox;
	}
	
	@Override
	public String getText() {
		return getField().getText();
	}
	
	@Override
	public void setEnabled(boolean enabled) {
		super.setEnabled(enabled);
		getField().setEnabled(enabled);
	}
	
	@Override
	public void setText(String text) {
		getField().setText(text);
	}

	protected TextBox createTextBox() {
		return new TextBox();
	}
}
